/* 批量冻结与解冻页
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaAdjust\component\BatchFreeze.tsx
 * @Date: 2021-08-31 09:39:33
 * @LastEditTime: 2021-09-14 16:34:43
 */
import udMainStore from '@/store/UdMain'
import React, { createRef } from 'react'
import { UdTable, http, validators, UdForm, UdModal, UdFilter, UdYearPicker, IUdFormItem } from '@/lib'
import UdUploader from '@/components/UdUploader/Uploader'
import { Input, Select, message, Tooltip, TreeSelect, Button, Upload } from 'antd'
import apis from '@/apis'
import quotaApis from '@/apis/AboutQuota'
import inputApis from '@/apis/StatementOfAccount/index'
import todoApi from '@/apis/TodoList/index'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import QuotaApprove from '@/components/getQuotaApprove'
import UdSelect from '@/components/UdFormControls/UdSelect'
import Search from 'antd/lib/input/Search'
import { downBlobFileXlsx } from '@/utils/methods'
const { TextArea } = Input
const { Option } = Select
const { TreeNode } = TreeSelect
export default class BatchOperation extends React.Component<IProps, IState> {
  private modal
  private brandList = udMainStore.brandList
  private form: WrappedFormUtils
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private FROZEN_TYPE_ENUM: any = {
    SUSPEND: '暂停发货',
    VIOLATION: '违规',
    OTHER: '其他',
  }
  private PLAN_TYPE_ENUM: any = {
    0: '计划内',
    1: '计划外',
  }
  private planType: number = this.props.planType
  private frozenStatus: number = this.props.frozenStatus
  public cRef = createRef<any>()
  constructor(props) {
    super(props)
    this.state = {
      uploading: false,
      downloading: false,
      treeDataList: [],
      prodBarCodeList: [],
      dataSource: [],
      workFlowList: [],
      checkPerson: [],
      values: {},
      loading: false,
      isApprove: {
        quotaFreeze: false,
      },
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          initialValue: this.brandList[0].value,
          render: (
            <UdSelect
              showSearch
              allowClear={false}
              options={this.brandList}
              onChange={value => {
                this.changeBrandCode(value)
              }}
            />
          ),
        },
        {
          label: '片区',
          id: 'belongAreaCode',
          render: () => (
            <TreeSelect showSearch treeNodeFilterProp="title">
              {this.mapTree(this.state.treeDataList)}
            </TreeSelect>
          ),
        },
        {
          label: '配额品项',
          id: 'prodBarcode',
          render: () => <UdSelect showSearch options={this.state.prodBarCodeList} />,
        },
        {
          label: '客户编码',
          id: 'dealerCode',
          render: () => (
            <Search
              placeholder="请输入客户编码"
              enterButton="导入编码"
              onSearch={() => this.handImportCodeFileExcel()}
            />
          ),
        },
        { label: '客户名称', id: 'dealerName' },
        {
          id: 'stageYear',
          label: '考核年度',
          render: () => <UdYearPicker className={'ext'} />,
        },
        { label: '考核阶段', id: 'stageName' },
        {
          label: '计划类型',
          id: 'planType',
          initialValue: this.planType,
          render: (
            <Select disabled={true}>
              <Option value={0}>计划内</Option>
              <Option value={1}>计划外</Option>
            </Select>
          ),
        },
        {
          label: '冻结状态',
          id: 'frozenStatus',
          initialValue: this.frozenStatus,
          render: (
            <Select disabled={true}>
              <Option value={0}>未冻结</Option>
              <Option value={1}>已冻结</Option>
            </Select>
          ),
        },
      ] as IUdFormItem[],
    }
  }

  componentDidMount() {
    // let params = {
    //   brandCode: this.dataSource[0]['brandCode'],
    //   prodBarcode: [...new Set(this.dataSource.map(item => item.prodBarcode))].join(','),
    // }
    // http.get(todoApi.getProcessKeyFlow, { params }).then(res => {
    //   this.setState(
    //     {
    //       isApprove: res.data,
    //     },
    //     () => {
    //       if (res?.data?.quotaFreeze) {
    //         this.getWorkFlow()
    //       }
    //     }
    //   )
    // })
    this.setState(
      {
        values: {
          planTypeText: this.PLAN_TYPE_ENUM[this.planType],
          frozenStatusText: this.frozenStatus === 0 ? '冻结' : '解冻',
        },
      },
      () => {
        this.changeBrandCode(this.filterForm.getFieldValue('brandCode'))
      }
    )
  }

  private changeBrandCode = (value: any): void => {
    this.filterForm.setFieldsValue({ prodBarcode: undefined, belongAreaCode: undefined }, () => {
      this.setState({ prodBarCodeList: [], treeDataList: [] }, () => {
        Promise.allSettled([this.getProdBarList(value), this.getAreaList(value)]).then((res: any) => {
          this.setState(
            {
              prodBarCodeList: res[0]?.value || [],
              treeDataList: res[1]?.value || [],
            },
            () => {
              this.filterForm.setFieldsValue({ prodBarcode: this.state.prodBarCodeList?.[0]?.value }, () => {
                this.getTableData()
              })
            }
          )
        })
      })
    })
  }
  private getAreaList = (value: any) => {
    return http
      .get(apis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  private getProdBarList = (value: any): Promise<any> => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        return prodBarCodeList
      })
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }

  private getTableData = async () => {
    this.setState({ loading: true })
    let params = {
      conditions: this.filterForm.getFieldsValue(),
    }
    http
      .post(quotaApis.getBatchFrozenDetailPage, params)
      .then(res => {
        console.log('res', res)
      })
      .finally(() => {
        this.setState({
          loading: false,
        })
      })
  }

  private handleSearch = (values: any) => {
    this.setState({ dataSource: [], page: 1, total: 0 }, () => {
      this.getTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.changeBrandCode(this.filterForm.getFieldValue('brandCode'))
  }

  private handImportCodeFileExcel = () => {
    //客户编码模板导入
    this.modal = UdModal.open({
      title: '导入客户编码',
      width: 300,
      content: (
        <>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Button type="primary" onClick={this.handDownloadTemplate}>
              下载模板
            </Button>
            <Upload showUploadList={false} customRequest={this.handImportTemplate}>
              <Button type="primary">导入配额</Button>
            </Upload>
          </div>
        </>
      ),
      footer: null,
      maskClosable: true,
      centered: true,
    })
  }

  //客户编码模板下载
  private handDownloadTemplate = () => {
    http
      .get(quotaApis.downloadQuotaAgentImportExcel, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFileXlsx(res.data, `配额调整-客户编码导入模板`)
        }
      })
      .catch(err => {
        console.log(err)
      })
  }

  //客户编码模板导入
  private handImportTemplate = option => {
    this.modal && this.modal.destroy()
    const { file } = option
    const formData = new FormData()
    formData.append('file', file)
    let { brandCode } = this.filterForm.getFieldsValue()
    if (!brandCode) {
      message.warn('请选择品牌公司')
      return
    }
    let params: any = { brandCode }
    formData.append('agentLetterReqVo', new Blob([JSON.stringify(params)], { type: 'application/json' }))
    return http.post(inputApis.agentletterLaunchImport, formData, { timeout: 1000 * 60 * 10 }).then(res => {
      const dataSource = res?.data ?? []
      this.filterForm.setFieldsValue({ dealerCode: dataSource.map(e => e.agentCode).join(',') })
    })
  }

  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        let { isApprove, dataSource } = this.state
        if (isApprove?.quotaFreeze && this.state.checkPerson.length === 0) {
          message.warn('请选择审批人')
          return false
        }
        e.drawerBtnLoading()
        let ids = dataSource.map(({ id, idWay }) => id).join(',')
        let formValues = this.form.getFieldsValue()
        delete formValues.frozenStatusText
        delete formValues.planTypeText
        const params = {
          ids,
          brandCode: dataSource[0]?.brandCode,
          brandName: dataSource[0]?.brandName,
          frozenStatus: this.frozenStatus === 0 ? 1 : 0,
          ...formValues,
        }
        if (this.frozenStatus === 1) {
          params['frozenType'] = dataSource[0]?.frozenType
        }
        if (this.state.checkPerson.length > 0) {
          params['workflowReqVos'] = {
            name: 'candidateUsers',
            userId: [this.state.checkPerson[0].id],
          }
        }
        http
          .post(quotaApis.batchFreeze, params)
          .then(res => {
            this.props.refresh()
            message.success('操作成功')
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
      } else {
        console.log(err)
      }
    })
  }

  //获取审批角色
  private getWorkFlow = () => {
    let { dataSource } = this.state
    http.get(todoApi.getFreezeNextApprove, { params: { brandCode: dataSource[0]['brandCode'] } }).then(res => {
      const { data } = res
      this.setState({ workFlowList: data })
    })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  render() {
    let { isApprove, dataSource } = this.state
    const items = [
      {
        label: '申请类型',
        id: 'frozenStatusText',
        render: <Input readOnly />,
      },
      {
        label: '计划类型',
        id: 'planTypeText',
        render: <Input readOnly />,
      },
      {
        label: '冻结原因',
        id: 'frozenType',
        rules: [validators.required],
        render: (
          <Select>
            <Option value="SUSPEND">暂停发货</Option>
            <Option value="VIOLATION">违规</Option>
            <Option value="OTHER">其他</Option>
          </Select>
        ),
      },
      { label: '备注信息', id: 'remark', render: <TextArea rows={3} /> },
      {
        label: '凭证附件',
        id: 'quotaApplyDetailFileRespVoList',
        render: <UdUploader form={this.form} extra="支持扩展名：.jpg .png .xls .doc" />,
      },
    ]
    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        width: 50,
        render: (text, record, index) => index + 1,
      },
      { title: '客户编码', dataIndex: 'dealerCode' },
      { title: '客户名称', dataIndex: 'dealerName' },
      { title: '品牌公司', dataIndex: 'brandName' },
      { title: '配额品项', dataIndex: 'prodBarname' },
      { title: '考核年度', dataIndex: 'stageYear', width: 80 },
      {
        title: '考核阶段',
        dataIndex: 'stageName',
        width: 80,
        render: (text, record) => {
          return (
            <Tooltip title={record.stageName}>
              <div style={{ width: '80px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.stageName}
              </div>
            </Tooltip>
          )
        },
      },
      {
        title: '冻结原因',
        dataIndex: 'frozenType',
        render: (text, record, index) => {
          return this.FROZEN_TYPE_ENUM[record.frozenType]
        },
      },
    ]
    return (
      <>
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.state.conditions}
          onSearch={values => {}}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdTable
          rowKey="id"
          columns={
            this.frozenStatus === 1
              ? columns
              : columns.filter(item => {
                  return item.dataIndex !== 'frozenType'
                })
          }
          dataSource={dataSource}
          onChange={pagination => {
            this.setState({ pagination })
          }}
          //   pagination={this.state.pagination}
        />
        <div>&nbsp;</div>
        <UdForm
          getForm={form => (this.form = form)}
          items={
            this.frozenStatus === 0
              ? items
              : items.filter(item => {
                  return item.id !== 'frozenType'
                })
          }
          values={this.state.values}
        />
        {isApprove?.quotaFreeze && <h4>审批流程</h4>}
        {isApprove?.quotaFreeze && (
          <div className="approve-wrap">
            <div className="node-name-wrap">
              <div className="title">节点名称：</div>
              <span className="circle-point"></span>
              <div>{this.state.workFlowList[0]?.nodeName || '暂无'}</div>
            </div>
            <div className="person-name-wrap">
              <div className="title">审批人:</div>
              <div
                className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
                onClick={() => {
                  this.handShowQuotaApprove(0)
                }}
              >
                {this.state.checkPerson[0]?.realName || '+'}
              </div>
            </div>
          </div>
        )}
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        />
      </>
    )
  }
}

interface IProps {
  frozenStatus: number
  planType: number
  refresh?: any
  isApprove?: any
}
interface IState {
  uploading: boolean
  downloading: boolean
  treeDataList: any[]
  prodBarCodeList: any[]
  conditions: any[]
  isApprove?: any
  dataSource?: any
  values: any
  loading: boolean
  page?: number
  size?: number
  total?: number
  pagination?: any
  workFlowList?: any[]
  checkPerson?: any[]
}
